﻿using DLL.NET.DB.MS.Drugs.CRUD.Service;
using DLL.NET50.DB.MS.ORM.Service;
using DLL.NET60.DB.MS.Entity.DTO;
using DLL.NET70.Infrastructure.Prism;
using DLL.NET70.Infrastructure.Prism.MVVM;
using DLL.Standard.Infrastructure.Entity;
using DLL.Standard.Infrastructure.Log;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using PrismModule.MS.WorkFile;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace PrismModule.WorkFile.ViewModels
{
    public class PUC_AddWorkFileViewModel : CMVVMBase, IRegionMemberLifetime
    {
        #region property

        private DTO_adi_work_file _editObject = new DTO_adi_work_file();

        public DTO_adi_work_file EditObject
        {
            get { return _editObject; }
            set
            {
                SetProperty(ref _editObject, value);
            }
        }

        private DTO_adi_work_file _oldObject = new DTO_adi_work_file();

        public DTO_adi_work_file oldObject
        {
            get { return _oldObject; }
            set
            {
                SetProperty(ref _oldObject, value);
            }
        }

        private bool _isAdd = false;

        public bool IsAdd
        {
            get { return _isAdd; }
            set { SetProperty(ref _isAdd, value); }
        }

        private List<DTO_adi_dic_drug> _drus = new List<DTO_adi_dic_drug>();

        public List<DTO_adi_dic_drug> drugs
        {
            get { return _drus; }
            set
            {
                SetProperty(ref _drus, value);
            }
        }

        private List<DTO_adi_dic_drug> _solvents = new List<DTO_adi_dic_drug>();

        public List<DTO_adi_dic_drug> Solvents
        {
            get { return _solvents; }
            set
            {
                SetProperty(ref _solvents, value);
            }
        }

        private ObservableCollection<string> _drugCodes = new ObservableCollection<string>();

        public ObservableCollection<string> DrugCodes
        {
            get { return _drugCodes; }
            set
            {
                SetProperty(ref _drugCodes, value);
            }
        }

        private DTO_adi_dic_drug _cbxNameSelectItem;

        public DTO_adi_dic_drug cbxNameSelectItem
        {
            get { return _cbxNameSelectItem; }
            set { SetProperty(ref _cbxNameSelectItem, value); }
        }

        private int _cbxNameSelectIndex = -1;

        public int cbxNameSelectIndex
        {
            get { return _cbxNameSelectIndex; }
            set { SetProperty(ref _cbxNameSelectIndex, value); }
        }

        private DTO_adi_dic_drug _cbxSolventNameSelectItem;

        public DTO_adi_dic_drug cbxSolventNameSelectItem
        {
            get { return _cbxSolventNameSelectItem; }
            set { SetProperty(ref _cbxSolventNameSelectItem, value); }
        }

        private int _cbxSolventNameSelectIndex = -1;

        public int cbxSolventNameSelectIndex
        {
            get { return _cbxSolventNameSelectIndex; }
            set { SetProperty(ref _cbxSolventNameSelectIndex, value); }
        }

        private string _cbxCodeSelectItem;

        public string cbxCodeSelectItem
        {
            get { return _cbxCodeSelectItem; }
            set { SetProperty(ref _cbxCodeSelectItem, value); }
        }

        private ComboBoxItem _cbxCountSelectItem;

        public ComboBoxItem cbxCountSelectItem
        {
            get { return _cbxCountSelectItem; }
            set { SetProperty(ref _cbxCountSelectItem, value); }
        }

        private int _cbxCountSelectIndex = -1;

        public int cbxCountSelectIndex
        {
            get { return _cbxCountSelectIndex; }
            set { SetProperty(ref _cbxCountSelectIndex, value); }
        }

        private int _cbxCodeSelectIndex = -1;

        public int cbxCodeSelectIndex
        {
            get { return _cbxCodeSelectIndex; }
            set { SetProperty(ref _cbxCodeSelectIndex, value); }
        }

        #endregion property

        #region navigate

        public bool KeepAlive
        {
            get
            {
                return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
            }
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            journal = navigationContext.NavigationService.Journal;
            GoForwardCommand.RaiseCanExecuteChanged();
            GoBackCommand.RaiseCanExecuteChanged();
            oldObject = navigationContext.Parameters["Workfile"] as DTO_adi_work_file;
            if (oldObject != null)
            {
                EditObject = (DTO_adi_work_file)oldObject;
            }
        }

        #endregion navigate

        private IMSDrugsService _drugService;
        private IContainerExtension _container;
        private IWorkFileService _workFileService;

        public PUC_AddWorkFileViewModel(IRegionManager regionManager,
            IEventAggregator eventAggregator,
            IContainerExtension container,
            IMSDrugsService drugsService,
            IApplicationCommands applicationCommands,
            IWorkFileService workFileService) : base(regionManager, eventAggregator, applicationCommands)
        {
            _drugService = drugsService;
            _workFileService = workFileService;
            _container = container;
            ComboxSolventNameSelectItemChangedCommand = new DelegateCommand(NotifySolventNameSelectedItemChanged);
            ComboxNameSelectItemChangedCommand = new DelegateCommand(NotifyNameSelectedItemChanged);
            ComboxCodeSelectItemChangedCommand = new DelegateCommand(NotifyCodeSelectedItemChanged);
            ComboxCountSelectItemChangedCommand = new DelegateCommand(NotifyCountSelectedItemChanged);
            ComboxModeSelectItemChangedCommand = new DelegateCommand(NotifyModeSelectedItemChanged);
        }

        #region window load

        public override void Loaded()
        {
            LogHelper.Debug("PUC_AddWorkFileViewModel  初始化");
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start(); //  开始监视代码
            RegisterSaveCommand();
            EventAggregator.GetEvent<CEditWorkFileEvent>().Subscribe(ReceiveEditWorkFileMsg);
            drugs = _drugService.GetDrugs(d => d.SOLVENT_FLAG != null && d.NEEDLE_TYPE != null && d.SOLVENT_FLAG != 1);
            Solvents = _drugService.GetDrugs(d => d.SOLVENT_FLAG != null && d.SOLVENT_FLAG == 1);
            LogMessage("用时=" + GetUsedTotalTime(stopwatch).ToString() + "ms");

            base.Loaded();
        }

        public override void UnLoaded()
        {
            UnRegisterSaveCommand();
            EventAggregator.GetEvent<CEditWorkFileEvent>().Unsubscribe(ReceiveEditWorkFileMsg);
            base.UnLoaded();
        }

        #endregion window load

        private void ReceiveEditWorkFileMsg(DTO_adi_work_file accountDTO)
        {
            if (accountDTO == null)
            {
                EditObject = new DTO_adi_work_file();// (adi_accountDTO)account.Clone();
            }
            else
            {
                EditObject = accountDTO;// (adi_accountDTO)account.Clone();
            }
        }

        #region delegate function

        public override void Save()
        {
            try
            {
                //添加判断该药品的属性是否都已经设置
                if ((EditObject.DRUG_COUNT < 1) || (EditObject.DRUG_NAME == null) || (EditObject.ErKeMode < 0) || (EditObject.DRUG_CODE.Length == 0) || (EditObject.REALDOSE == 0))
                {
                    //MessageBox.Show();
                    LogMessage("有的数据没有设置，保存失败！", LogLevel.Warning);
                    return;
                }
                if (EditObject.ErKeMode == 1)
                {
                    //儿科模式
                    if ((EditObject.REALDOSE >= EditObject.DOSE) || (EditObject.REALDOSE <= 0))
                    {
                        MessageBox.Show("儿科模式，实际使用剂量设置有误，保存失败！");
                        return;
                    }
                    if (EditObject.DRUG_COUNT > 1)
                    {
                        MessageBox.Show("儿科模式，西林瓶的数量只能为1，保存失败！");
                        return;
                    }
                }
                else if (EditObject.ErKeMode == 0)
                {
                    //整只模式
                    //if (EditObject.REALDOSE != EditObject.DRUG_COUNT * EditObject.DOSE)
                    //{
                    //    MessageBox.Show("整只模式，实际使用剂量设置有误，保存失败！");
                    //    return;
                    //}
                }

                string name = "";
                if (EditObject.ErKeMode == 0)
                {
                    name = "不结余";
                }
                else if (EditObject.ErKeMode == 1)
                {
                    name = "结余";
                }

                List<DTO_adi_dic_drug> drugs = _drugService.SearchDrugsByDrugCode(EditObject.DRUG_CODE);
                if (drugs.Count == 1)
                {
                    //bool bret = CDrugInitialize.PropertyIsSet(drugs[0]);
                    //if (false == ret)
                    //{
                    //    MessageBox.Show("药品属性没有设置，保存失败！");
                    //    return;
                    //}
                }
                EditObject.FILE_NAME = EditObject.DRUG_NAME + "-" + EditObject.DOSE.ToString() + "-" + name + "-" + EditObject.REALDOSE.ToString();
                bool ret = _workFileService.SaveWorkFile(EditObject);
                if (true == ret)
                {
                    EditObject = new DTO_adi_work_file();
                    cbxCodeSelectIndex = -1;
                    cbxNameSelectIndex = -1;
                    cbxCountSelectIndex = -1;

                    SendCommandMessage(GlobalCommand.SaveOK);
                    LogMessage("数据保存成功！");
                }
                else
                {
                    LogMessage("数据保存失败！");
                }
            }
            catch (Exception e)
            {
                LogHelper.Warn("单机文件保存出现异常：" + e.Message);
            }
        }

        #endregion delegate function

        #region combox 处理函数

        public DelegateCommand ComboxSolventNameSelectItemChangedCommand { get; set; }
        public DelegateCommand ComboxNameSelectItemChangedCommand { get; set; }
        public DelegateCommand ComboxCodeSelectItemChangedCommand { get; set; }
        public DelegateCommand ComboxCountSelectItemChangedCommand { get; set; }
        public DelegateCommand ComboxModeSelectItemChangedCommand { get; set; }

        //构造函数中

        //事件：
        //药品名称更改
        public void NotifySolventNameSelectedItemChanged()
        {
            try
            {
                //获取该药名称对应的所有药品编码
                if ((cbxSolventNameSelectItem == null))
                {
                    return;
                }
                string name = cbxSolventNameSelectItem.DRUG_NAME.ToString();
                EditObject.Solvent_Name = name;
                EditObject.Solvent_Code = cbxSolventNameSelectItem.DRUG_CODE.ToString();
            }
            catch (Exception e)
            {
                LogHelper.Warn("选择药品名称出现异常：" + e.Message);
            }
        }

        public void NotifyNameSelectedItemChanged()
        {
            try
            {
                //获取该药名称对应的所有药品编码
                if ((cbxNameSelectItem == null))
                {
                    return;
                }
                DrugCodes.Clear();
                string name = cbxNameSelectItem.DRUG_NAME.ToString();
                EditObject.DRUG_NAME = name;
                List<DTO_adi_dic_drug> ldrugs = _drugService.SearchDrugsByName(name);
                if (ldrugs.Count > 0)
                {
                    foreach (var drug in ldrugs)
                    {
                        DrugCodes.Add(drug.DRUG_CODE);
                    }
                    EditObject.DRUG_COUNT = 0;
                    EditObject.REALDOSE = 0;
                    EditObject.DRUG_CODE = "";
                    cbxCountSelectIndex = -1;
                }
            }
            catch (Exception e)
            {
                LogHelper.Warn("选择药品名称出现异常：" + e.Message);
            }
        }

        //药品编码更改
        public void NotifyCodeSelectedItemChanged()
        {
            try
            {
                if ((cbxCodeSelectItem == null))
                {
                    return;
                }
                string code = cbxCodeSelectItem.ToString();
                List<DTO_adi_dic_drug> ldrugs = _drugService.SearchDrugsByDrugCode(code);
                if (ldrugs.Count > 0)
                {
                    EditObject.DRUG_PYCODE = ldrugs[0].PY_CODE;
                    EditObject.DOSE = ldrugs[0].DOSE;
                    EditObject.DOSE_UNIT = ldrugs[0].DOSE_UNIT;
                    EditObject.DRUG_NAME = ldrugs[0].DRUG_NAME;
                    EditObject.DRUG_CODE = code;
                    EditObject.DRUG_COUNT = 0;
                    EditObject.REALDOSE = 0;
                    cbxCountSelectIndex = -1;
                    //EditObject.FILE_NAME = EditObject.DRUG_NAME + "-" + EditObject.DOSE.ToString() + "-" +;
                }
            }
            catch (Exception e)
            {
                LogHelper.Warn("选择药品编码出现异常：" + e.Message);
            }
        }

        public void NotifyCountSelectedItemChanged()
        {
            try
            {
                if (cbxCountSelectItem == null)
                {
                    return;
                }
                string content = cbxCountSelectItem.Content.ToString();
                EditObject.DRUG_COUNT = Convert.ToInt32(content);

                EditObject.REALDOSE = Convert.ToSingle((EditObject.DRUG_COUNT * EditObject.DOSE).ToString("0.###"));
            }
            catch (Exception e)
            {
                LogHelper.Warn("出现异常：" + e.Message);
            }
        }

        public void NotifyModeSelectedItemChanged()
        {
            try
            {
                switch (EditObject.ErKeMode)
                {
                    case 0:
                        LogMessage("整只模式配药：配药是整只");
                        break;

                    case 1:
                        LogMessage("儿科模式：一支药对应多袋溶媒！");
                        break;

                    case 2:
                        LogMessage("非整只模式：配的药有整只和非整只的");
                        break;

                    case 3:
                        LogMessage("专用溶媒模式：用专用的溶媒配药，然后在回打溶媒");
                        break;

                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                LogHelper.Warn("出现异常：" + e.Message);
            }
        }

        #endregion combox 处理函数
    }
}